﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RWLibrary.Logic.Queries
{
    using Graph;
    public class AccessibilityQuery : Query
    {
        public AccessibilityQuery(Graph graph) : base(graph)
        {
        }

        public BooleanExpression.IBooleanExpression Goal { get; set; }
        public List<string> Actions { get; set; }
        public BooleanExpression.IBooleanExpression Pi { get; set; }

        public override bool Excecute()
        {

            HashSet<Node> actualPositions = new HashSet<Node>( Graph.Nodes.Where(n => Pi.Test(n.State)));

            foreach (var action in Actions)
            {
                HashSet<Node> nextPositions = new HashSet<Node>();
                foreach (var actualPosition in actualPositions)
                {
                    foreach (var e in actualPosition.Connections.Where(e => e.Key.Name == action))
                    {
                        if (!nextPositions.Contains(e.Value))
                            nextPositions.Add(e.Value);
                        
                    }
                }
                actualPositions = nextPositions;
            }
            foreach (var position in actualPositions)
                if (Goal.Test(position.State))
                    return true;
            return false;
        }

    }
}
